package com.rxtxdemo.rxtxdemo.demo;

import com.rxtxdemo.rxtxdemo.applicationevent.publish.IComService;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SerialService {

    @Autowired
    private IComService comService;

    @Autowired
    @Qualifier(value = "asyncExecutor")
    private ThreadPoolTaskExecutor poolTaskExecutor;

    public void test() {
        OrderList oList = new OrderList();
        oList.init();
        List<Order> list = oList.setV();
        log.info("开始执行--------");
        long a = System.currentTimeMillis();
        //获得串口操作实例
        SerialPortutil serialPortutil = SerialPortutil.getSerialPortutil();
        //获得操作的串口对象
        // 端口名称 波特率 数据位 停止位 校验位
        SerialPort S = serialPortutil.openSerialPort("COM8", 115200, 8, 1, 0);
        //设置监听类
        MyLister my = new MyLister();
        //设置串口设备状态执行策略类
        my.setComService(comService);
        //设置线程池
        my.setPoolTaskExecutor1(poolTaskExecutor);
        my.setCom(S);
        serialPortutil.setListenerToSerialPort(S, my);
        //分发给执行服务，执行指令
        list.stream().parallel().forEach(item -> {
            if (item.getComName().equals("COM8")) {
                serialPortutil.sendData(S, item.getOrderStr());
            }
        });
        System.out.println("list.stream().forEach 执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 ");
    }


}
